import axios, { AxiosRequestConfig, AxiosInstance } from 'axios'
import qs from 'qs'
import { useRoute } from 'vue-router'
import { useDayStore } from '../store/modules/dayState'
import pinia from '../store/index'

const useDayStore1 = useDayStore(pinia)
//http://apitest.wzxchat.cn/ 测试环境
//https://tyapi.wzxchat.cn/  生产环境
const defaultConfig: AxiosRequestConfig = {
  baseURL: 'https://tyapi.wzxchat.cn/api',
  timeout: 10000,
  // 数组格式参数序列化
  paramsSerializer: (params) => qs.stringify(params, { indices: false })
}

const instance: AxiosInstance = axios.create({
  ...defaultConfig
})

// export const token = 'c097fe67b8fd458db827ead8160d5ed9a55a405a'
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      // @ts-ignore
      // config.headers['Authorization'] = `Bearer ${token}`
      config.headers['token'] = `${token}`
    }
    useDayStore1.showLoading()
    return config
  },
  (error) => {
    useDayStore1.hideLoading()
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    useDayStore1.hideLoading()
    return response.data
  },
  (error) => {
    useDayStore1.hideLoading()
    return Promise.reject(error)
  }
)

export default instance
